define(function(require, exports, module) {
	module.exports = function() {
		var app = angular.module('ProjectManage.controllers');

		app.controller('projectsCtrl', ['$scope', '$http', '$timeout', '$rootScope', '$filter', 'allProjectsFunc', 'myProjectsFunc',
			function($scope, $http, $timeout, $rootScope, $filter, allProjectsFunc, myProjectsFunc) {

				$scope.allPrjs = [];
				$scope.filtered = [];
				$scope.paged = [];

				$scope.totalItems = 1;
				$scope.itemsPerPage = 10;
				$scope.currentPage = 1;

				$scope.pageChanged = function(page) {
					// body...
					$scope.paged = $scope.filtered.slice($scope.itemsPerPage * (page - 1), $scope.itemsPerPage * (page - 1) + $scope.itemsPerPage);
					$scope.currentPage = page;

				}

				function GetPrjAll() {
					allProjectsFunc.getAllProjects(function() {
						ApplyFilterAndPage();
					});
				}

				function ApplyFilterAndPage() {
					$scope.allPrjs = $rootScope.projects;
					$scope.$watch('searchTxt', function(newValue) {
						$scope.filtered = $filter('filter')($scope.allPrjs, $scope.searchTxt);
						$scope.totalItems = $scope.filtered.length;
						$scope.paged = $scope.filtered.slice(0, $scope.itemsPerPage);
						$scope.currentPage = 1;
					});
					$scope.searchTxt = $rootScope.user.name;
				}
				$timeout(GetPrjAll, 900);

				$scope.clickFavor = function(prj) {
					prj.isFavor = !prj.isFavor;
					if (prj.isFavor === true) {
						var index = toBeDelete.indexOf(prj.PrjId);
						if (index > -1) {
							toBeDelete.splice(index, 1);
						} else {
							toBeAdd.push(prj.PrjId);
						}
						myProjectsFunc.addMyProject(prj);
					} else {
						var index = toBeAdd.indexOf(prj.PrjId);
						if (index > -1) {
							toBeAdd.splice(index, 1);
						} else {
							toBeDelete.push(prj.PrjId);
						}
						myProjectsFunc.removeMyProject(prj);
					}
				};
				var toBeAdd = [];
				var toBeDelete = [];
				$scope.$on("$destroy", function() {
					myProjectsFunc.addFavorProjects(toBeAdd);
					myProjectsFunc.removeFavorProjects(toBeDelete);
				});

			}
		]);
	};
});